﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PathFinding
{
	public class Utils
	{
		public static void FillNeighbours(IIntersection[,] grid)
		{
			int xLen = grid.GetLength(0);
			int yLen = grid.GetLength(1);

			for (int y = 0; y < yLen; y++)
			{
				for (int x = 0; x < xLen; x++)
				{
					if (grid[x, y] != null) SetNeighbours(grid[x, y], xLen, yLen, grid);
				}
			}
		}

		public static void SetNeighbours2(IIntersection intersection, int xLen, int yLen, IIntersection[,] grid)
		{
			List<IIntersection> neighbours = new List<IIntersection>();
			if (intersection.X > 0 && grid[intersection.X - 1, intersection.Y] != null) neighbours.Add(grid[intersection.X - 1, intersection.Y]);
			if (intersection.X < (xLen - 1) && grid[intersection.X + 1, intersection.Y] != null) neighbours.Add(grid[intersection.X + 1, intersection.Y]);
			if (intersection.Y > 0 && grid[intersection.X, intersection.Y - 1] != null) neighbours.Add(grid[intersection.X, intersection.Y - 1]);
			if (intersection.Y < (yLen - 1) && grid[intersection.X, intersection.Y + 1] != null) neighbours.Add(grid[intersection.X, intersection.Y + 1]);

			intersection.Neighbours = neighbours.ToArray();
		}

		public static void SetNeighbours(IIntersection intersection, int xLen, int yLen, IIntersection[,] grid)
		{
			if (intersection != null)
			{
				List<IIntersection> neighbours = new List<IIntersection>();
				int minX = (intersection.X == 0) ? 0 : intersection.X - 1;
				int maxX = (intersection.X == (xLen - 1)) ? intersection.X : intersection.X + 1;
				int minY = (intersection.Y == 0) ? 0 : intersection.Y - 1;
				int maxY = (intersection.Y == (yLen - 1)) ? intersection.Y : intersection.Y + 1;

				for (int x = minX; x <= maxX; x++)
				{
					for (int y = minY; y <= maxY; y++)
					{
						if (!(x == intersection.X && y == intersection.Y))
						{
							if (grid[x, y] != null) neighbours.Add(grid[x, y]);
						}
					}
				}
				intersection.Neighbours = neighbours.ToArray();
			}
		}

		public static List<IIntersection> GetNeighbours(IIntersection intersection, IIntersection[,] grid)
		{
			int xLen = grid.GetLength(0);
			int yLen = grid.GetLength(1);

			List<IIntersection> neighbours = new List<IIntersection>();
			if (intersection != null)
			{
				int minX = (intersection.X == 0) ? 0 : intersection.X - 1;
				int maxX = (intersection.X == (xLen - 1)) ? intersection.X : intersection.X + 1;
				int minY = (intersection.Y == 0) ? 0 : intersection.Y - 1;
				int maxY = (intersection.Y == (yLen - 1)) ? intersection.Y : intersection.Y + 1;

				for (int x = minX; x <= maxX; x++)
				{
					for (int y = minY; y <= maxY; y++)
					{
						if (!(x == intersection.X && y == intersection.Y))
						{
							if (grid[x, y] != null) neighbours.Add(grid[x, y]);
						}
					}
				}
			}
			return neighbours;
		}
	}
}
